/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package eu.fastl.dragster.loadgen.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.math.stat.descriptive.SynchronizedSummaryStatistics;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import eu.fastl.dragster.loadgen.UrlProvider;

/**
 * Main class for generating HTTP Load
 *
 * @author Ernst Fastl
 */
public class HttpLoadGenerator {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpLoadGenerator.class);

    private final List<Thread> threads = new ArrayList<Thread>();

    private final HttpLoadGeneratorConfig config;

    private final UrlProvider provider;

    private long startTimeInMillis;

    private long finalTime;

    private final SynchronizedSummaryStatistics statistics = new SynchronizedSummaryStatistics();

    private final Map<Integer, AtomicLong> requestStatusMap = Collections
            .synchronizedMap(new HashMap<Integer, AtomicLong>());

    public HttpLoadGenerator(HttpLoadGeneratorConfig config) {
        super();
        this.config = config;
        this.provider = createProvider();
    }

    public void run() {
        LOGGER.info("Starting Load Generator with " + this.config.getNumThreads() + " threads...");
        if (StringUtils.isNotBlank(this.config.getFileName()))
            LOGGER.info("Reading file:" + this.config.getFileName());
        LOGGER.info("Number of runs:" + this.config.getNumRuns());

        LOGGER.info("Creating threads...");
        for (int i = 0; i < this.config.getNumThreads(); i++) {
            HttpLoadGeneratorThread httpLoadGeneratorThread = new HttpLoadGeneratorThread(this);
            this.threads.add(httpLoadGeneratorThread);
        }

        this.startTimeInMillis = System.currentTimeMillis();

        LOGGER.info("Starting threads...");
        for (Thread thread : this.threads) {
            thread.start();
        }
        while (atLeastOneThreadisRunning()) {
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.finalTime = System.currentTimeMillis() - this.startTimeInMillis;
        printSummary();
    }

    private void printSummary() {
        long numQueries = this.statistics.getN();
        double seconds = (double) this.finalTime / 1000;
        double queriesPerSecond = numQueries / seconds;

        System.out.printf("Total time: %.3f s\n", seconds);
        System.out.println("Total number of queries: " + numQueries);
        System.out.printf("Queries per Second: %.2f\n", queriesPerSecond);
        System.out.printf("Average response time: %.2f ms\n", this.statistics.getMean());
        System.out.printf("Minimum response time: %.0f ms\n", this.statistics.getMin());
        System.out.printf("Maximum response time: %.0f ms\n", this.statistics.getMax());

        List<Integer> statusList = new ArrayList<Integer>(this.requestStatusMap.keySet());
        Collections.sort(statusList);
        for (Integer status : statusList) {
            long numRequests = this.requestStatusMap.get(status).longValue();
            System.out.println("Number of requests with status " + status + ": " + numRequests);
            System.out.println("Percentage of requests with status " + status + ": "
                    + ((numRequests * 100) / numQueries) + "%");
        }

        System.out.println();
    }

    public HttpClient createHttpClient() {
        return new DefaultHttpClient();
    }

    public boolean isTimeUp() {
        if (this.config.getSeconds() == 0) {
            return false;
        } else {
            long elapsedTime = System.currentTimeMillis() - this.startTimeInMillis;
            return this.config.getSeconds() * 1000 < elapsedTime;
        }
    }

    public UrlProvider getProvider() {
        return this.provider;
    }

    public SynchronizedSummaryStatistics getStatistics() {
        return this.statistics;
    }

    public HttpLoadGeneratorConfig getConfig() {
        return this.config;
    }

    private UrlProvider createProvider() {
        if (StringUtils.isNotBlank(this.config.getFileName())) {
            try {
                return new FileReaderUrlProvider(this.config.getFileName(), this.config.getNumRuns());
            } catch (IOException e) {
                throw new IllegalStateException(e);
            }
        } else if (StringUtils.isNotBlank(this.config.getUrl())) {
            return new FixedUrlProvider(this.config.getUrl(), this.config.getNumRuns());
        } else {
            throw new IllegalStateException("Either fileName or url have to be set!");
        }
    }

    private boolean atLeastOneThreadisRunning() {
        for (Thread thread : this.threads) {
            if (thread.isAlive())
                return true;
        }
        return false;
    }

    public synchronized AtomicLong getRequestStatusCount(int requestStatus) {
        Integer key = Integer.valueOf(requestStatus);
        if (this.requestStatusMap.containsKey(key)) {
            return this.requestStatusMap.get(key);
        } else {
            AtomicLong value = new AtomicLong();
            this.requestStatusMap.put(key, value);
            return value;
        }
    }
}
